package cn.itcast.bos.service.take_delivery.impl;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.take_delivery.WayBillDao;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.take_delivery.WayBillService;

@Service
@Transactional
public class WayBillServiceImpl implements WayBillService {
	
	@Autowired
	private WayBillDao wayBillDao;

	@Override
	public void saveWayBill(WayBill model) {
		if(model.getOrder()!=null&&(model.getOrder().getId()==null||model.getOrder().getId()==0)){
			model.setOrder(null);
		}
		WayBill wayBill = wayBillDao.findByWayBillNum(model.getWayBillNum());
		if(wayBill==null){
			wayBillDao.save(model);
		}else{
			Integer id = wayBill.getId();
			Order order = wayBill.getOrder();
			try {
				BeanUtils.copyProperties(wayBill, model);
				wayBill.setId(id);
				wayBill.setOrder(order);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Page<WayBill> queryPageWayBill(Pageable pageable) {
		
		return wayBillDao.findAll(pageable);
	}

	@Override
	public WayBill findWayBillByWayBillNum(String wayBillNum) {
		
		return wayBillDao.findByWayBillNum(wayBillNum);
	}
}
